package com.drinks.yiniang.common.help;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;


import com.drinks.yiniang.R;
import com.drinks.yiniang.io.api.MainApiIO;
import com.drinks.yiniang.utils.SharedPreUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.pickerimage.utils.media.ImageTools;
import com.hansen.library.utils.ClipboardUtils;
import com.hansen.library.utils.StringUtils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;

import static com.hansen.library.pickerimage.utils.media.ImageTools.buildTransaction;

/**
 * Created by han on 2019/1/16 0016.
 */

public class ShareHelp {
    private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;

    private IWXAPI iwxapi;
    private Tencent mTencent;

    private Activity mActivity;

    private String shareAppName = "点酒";

    private String DEFAULT_TITLE = "点酒";

    public ShareHelp(Activity activity) {
        this.mActivity = activity;
    }

    /**
     * 分享到微信小程序
     *
     * @param talentId 达人id
     * @param page     分享的页面, 比如： page=task_answer
     * @param id       分享任务的id
     */
    public void wxShareImageUrlToMiniProgram(final String talentId, final String page, final String id, final String title, String imgUrl) {
        if(StringUtils.isEmpty(imgUrl)) {
            wxShareToMiniProgramBitmap(talentId, page, id, title, null);
            return;
        }

        ToastUtils.showShort(R.string.text_load_wx_share);

        //网络图片
        MainApiIO.getInstance().getBitmap(imgUrl, new APIRequestCallback<Bitmap, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(Bitmap bitmap) {
                wxShareToMiniProgramBitmap(talentId, page, id, title, bitmap);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort("分享失败-" + error._2);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 分享到微信小程序
     *
     * @param talentId 达人id
     * @param page     分享的页面, 比如： page=task_answer
     * @param id       分享任务的id
     */
    public void wxShareToMiniProgramBitmap(String talentId, String page, String id, String title, Bitmap bitmap) {
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APPID);
            iwxapi.registerApp(Constants.WX_APPID);

            if (!iwxapi.isWXAppInstalled()) {
                ToastUtils.showShort("请先安装手机版微信");
                return;
            }

            if (iwxapi.getWXAppSupportAPI() < TIMELINE_SUPPORTED_VERSION) {
                ToastUtils.showShort("该版本微信不支持分享");
                return;
            }
        }

        //用户id
        String userId = SharedPreUtils.getInstance().getUserID();

        if (StringUtils.isEmpty(title)) {
            title = DEFAULT_TITLE;
        }

        //小程序页面
        StringBuilder stringBuilder = new StringBuilder(Constants.PATH_MINI_PROGRAM);

        WXMiniProgramObject miniProgram = new WXMiniProgramObject();
        miniProgram.webpageUrl = "https://www.fenziun.com/download";//自定义
        miniProgram.userName = Constants.WX_MINI_PROGRAM_APPID;//小程序id
        miniProgram.path = stringBuilder.toString();//小程序页面
        miniProgram.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;/// 可选打开 开发版，

        final WXMediaMessage mediaMessage = new WXMediaMessage(miniProgram);
        mediaMessage.title = title;//自定义
        mediaMessage.description = title;//自定义

        if (bitmap == null) {
            bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.app_logo);
            mediaMessage.thumbData = ImageTools.bmpToByteArray(bitmap, 32);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "";
            req.scene = SendMessageToWX.Req.WXSceneSession;
            req.message = mediaMessage;

            iwxapi.sendReq(req);
        } else {//网络图片
            mediaMessage.thumbData = ImageTools.bmpToByteArray(bitmap, 32);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "";
            req.scene = SendMessageToWX.Req.WXSceneSession;
            req.message = mediaMessage;

            iwxapi.sendReq(req);
        }
    }

    //微信分享
    public void wxShareBitmap(final boolean isfriend, Bitmap thumBitmap) {
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APPID);
            iwxapi.registerApp(Constants.WX_APPID);

            if (!iwxapi.isWXAppInstalled()) {
                ToastUtils.showShort("请先安装手机版微信");
                return;
            }

            if (iwxapi.getWXAppSupportAPI() < TIMELINE_SUPPORTED_VERSION) {
                ToastUtils.showShort("该版本微信不支持分享");
                return;
            }
        }

        ToastUtils.showShort(R.string.text_load_wx_share);

        WXImageObject imgObj = new WXImageObject(thumBitmap);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap thumbBmp = Bitmap.createScaledBitmap(thumBitmap, 80, 80, true);

        msg.thumbData = ImageTools.bmpToByteArray(thumbBmp, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");
        req.message = msg;
        if (isfriend) {//好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {//朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        iwxapi.sendReq(req);
    }

    //微信分享
    public void wxShareUrl(final boolean isfriend, String url) {
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APPID);
            iwxapi.registerApp(Constants.WX_APPID);

            if (!iwxapi.isWXAppInstalled()) {
                ToastUtils.showShort(R.string.text_wx_is_install);
                return;
            }

            if (iwxapi.getWXAppSupportAPI() < TIMELINE_SUPPORTED_VERSION) {
                ToastUtils.showShort("该版本微信不支持分享");
                return;
            }
        }

        if (url == null) {
            return;
        }

        ToastUtils.showShort(R.string.text_load_wx_share);

        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = DEFAULT_TITLE;
        msg.description = "分享";

        Bitmap thumb = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.icon_login_wechat);
        msg.thumbData = ImageTools.bmpToByteArray(thumb, 32);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;

        if (isfriend) {//好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {//朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        iwxapi.sendReq(req);
    }

    private void doWXShare(WXMediaMessage mediaMessage, Bitmap thumBitmap, boolean isfriend) {
        mediaMessage.thumbData = ImageTools.bmpToByteArray(thumBitmap, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = mediaMessage;
        if (isfriend) {//好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        } else {//朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        }

        iwxapi.sendReq(req);
    }

    //复制链接
    public void copyLink(String targetUrl) {
        if (StringUtils.isEmpty(targetUrl)) {
            return;
        }
        ClipboardUtils.copyTextToClipboard(mActivity, targetUrl);
        ToastUtils.showShort(R.string.text_copy_success);
    }

    //qq图片分享
    public void qqShareImg(String imgUrl) {
        doQQShare(null, null, imgUrl, null, true);
    }

    //qq图片分享
    public void qqShareUrl(String url) {
        doQQShare(DEFAULT_TITLE, url, null, "#分享#", false);
    }

    //qq分享
    public void qqShare(String title, String targetUrl, String imgUrl, String summary) {
        doQQShare(title, targetUrl, imgUrl, summary, false);
    }

    //qq空间图片分享
    public void qqZoneShareImg(String imgUrl) {
        doqQQZoneShare(null, null, null, imgUrl, true);
    }

    public void qqZoneShare(String title, String summary, String targetUrl, String imgUrl) {
        doqQQZoneShare(title, summary, targetUrl, imgUrl, false);
    }

    //发起qq分享
    private void doQQShare(String title, String targetUrl, String imgUrl, String summary, boolean isOnlyImg) {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APPID, mActivity);
        }

        Bundle params = new Bundle();

        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, shareAppName);

        if (isOnlyImg) {
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        } else {
            params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        }

        if (imgUrl != null) {
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgUrl);
        }

        // QQ分享要在主线程做
        mTencent.shareToQQ(mActivity, params, qqShareListener);
    }

    //发起qq空间
    private void doqQQZoneShare(String title, String summary, String targetUrl, String imgUrl, boolean isOnlyImg) {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APPID, mActivity);
        }
        ArrayList<String> imageUrls = new ArrayList<String>();

        if (imgUrl == null) {
            return;
        }

        imageUrls.add(imgUrl);

        Bundle params = new Bundle();

        if (isOnlyImg) {
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE);
        } else {
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
        }

        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls);

        mTencent.shareToQzone(mActivity, params, qqShareListener);
    }

    public void publishToQzone(String title, String targetUrl, String imgUrl, String summary) {
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APPID, mActivity);
        }

        ArrayList<String> imageUrls = new ArrayList<String>();

        if (imgUrl == null) {
            return;
        }

        imageUrls.add(imgUrl);


        Bundle params = new Bundle();

        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl);

        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imageUrls);

        mTencent.publishToQzone(mActivity, params, qqShareListener);
    }

    public void qqResult(int requestCode, int resultCode, Intent data) {
        Tencent.onActivityResultData(requestCode, resultCode, data, qqShareListener);
    }


    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            ToastUtils.showShort("取消分享");
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            ToastUtils.showShort("分享成功");
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            ToastUtils.showShort("分享失败:code=" + e.errorCode + "," + e.errorMessage);
        }
    };

    public void releaseResource() {
        if (mTencent != null) {
            mTencent.releaseResource();
        }
    }
}
